/** 构造函数 */
import _ from 'lodash';
import { request, config } from '../configs';
import { paramsControl } from '../utils/util';

/**
 * 传入{key:url}结构的对象，构造一个service，替代原本的大量重复代码
 * 会改变传入的json路径对象，给里面每一项添加前缀
 * @param {Object} paths
 * @returns {Object}
 */
export default function makeApi(paths, methods = {}) {
	const obj = {};
	const reg = /:[a-zA-Z0-9]*/g;
	for (const k in paths) {
		paths[k] = `${config.apiPrefix}${paths[k]}`;
		obj[k] = paramsControl((params) => {
			const m = paths[k].match(reg) || [];
			if (typeof params !== 'object' && m.length) {
				params = { [m[0].slice(1)]: params };
			}
			const body = _.cloneDeep(params);
			const url = m.reduce((p, n) => {
				const key = n.slice(1);
				delete body[key];
				return p.replace(n, encodeURIComponent(params[key]));
			}, paths[k]);
			return request({
				url,
				method: methods[k] || 'post',
				data: params,
			});
		});
	}
	return obj;
}
